<template>
    <div>
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <el-button v-perms="['interface.interface_app_list/add']" type="primary" @click="handleAdd">
                    <template #icon>
                        <icon name="el-icon-Plus" />
                    </template>
                    新增
                </el-button>
                <el-tooltip content="接口文档预览" placement="top">
                    <el-button type="text" @click="handleOpenDocs" size="small">
                        <icon name="el-icon-Document" :size="16" />接口文档预览
                    </el-button>
                </el-tooltip>
            </div>
            <div class="mt-4">
                <el-table :data="pager.lists" :row-class-name="initRowExpansionState">
                    <el-table-column label="应用名称" prop="app_name" show-overflow-tooltip />
                    <el-table-column label="AppID" prop="id" show-overflow-tooltip />
                    <el-table-column label="API的key" show-overflow-tooltip>
                        <template #default="{ row }">
                            <div class="key-container">
                                <span v-if="!row.apiKeyExpanded">{{ row.api_key.substring(0, 4) }}****</span>
                                <span v-else>{{ row.api_key }}</span>
                                <el-button type="text" size="small"
                                    @click.stop="row.apiKeyExpanded = !row.apiKeyExpanded">
                                    {{ row.apiKeyExpanded ? '收起' : '展开' }}
                                </el-button>
                                <el-button type="text" size="small"
                                    @click.stop="copyToClipboard(row.api_key, 'API密钥复制成功')">
                                    复制
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="密钥key" show-overflow-tooltip>
                        <template #default="{ row }">
                            <div class="key-container">
                                <span v-if="!row.secretKeyExpanded">{{ row.secret_key.substring(0, 4) }}****</span>
                                <span v-else>{{ row.secret_key }}</span>
                                <el-button type="text" size="small"
                                    @click.stop="row.secretKeyExpanded = !row.secretKeyExpanded">
                                    {{ row.secretKeyExpanded ? '收起' : '展开' }}
                                </el-button>
                                <el-button type="text" size="small"
                                    @click.stop="copyToClipboard(row.secret_key, '密钥key复制成功')">
                                    复制
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="create_time" show-overflow-tooltip />
                    <el-table-column label="操作" width="180" fixed="right">
                        <template #default="{ row }">
                            <el-button v-perms="['interface.interface_app_list/edit']" type="primary" link
                                @click="handleEdit(row)">
                                查看
                            </el-button>
                            <el-button v-perms="['interface.interface_app_list/updateSecretKey']" type="danger" link
                                @click="handleUpdate(row.id)">
                                更新密钥
                            </el-button>
                            <el-button v-perms="['interface.interface_app_list/delete']" type="danger" link
                                @click="handleDelete(row.id)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <add-popup v-if="showEdit && isAdd" ref="addRef" :dict-data="dictData" @success="getLists"
            @close="showEdit = false" />
        <edit-popup v-if="showEdit && !isAdd" ref="editRef" :dict-data="dictData" :row-data="currentRow"
            @success="getLists" @close="showEdit = false" />
    </div>
</template>

<script lang="ts" setup name="interfaceAppListLists">
const handleOpenDocs = () => {
    window.open('https://docs.apipost.net/docs/detail/518ecc691071000?target_id=72af5ebbbc003', '_blank');
}
import { usePaging } from '@/hooks/usePaging'
import { useDictData } from '@/hooks/useDictOptions'
import {
    apiInterfaceAppListLists,
    apiInterfaceAppListDelete,
    apiInterfaceAppListUpdateSecretKey
} from '@/api/interface_app_list'
import { timeFormat } from '@/utils/util'
import feedback from '@/utils/feedback'
import AddPopup from './add.vue'
import EditPopup from './edit.vue'

const addRef = shallowRef<InstanceType<typeof AddPopup>>()
const editRef = shallowRef<InstanceType<typeof EditPopup>>()
// 是否显示编辑框
const showEdit = ref(false)
// 是否是新增操作
const isAdd = ref(true)
// 当前编辑行数据
const currentRow = ref(null)

// 查询条件
const queryParams = reactive({})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 获取字典数据
const { dictData } = useDictData('')

// 复制到剪贴板
const copyToClipboard = async (text, message) => {
    try {
        await navigator.clipboard.writeText(text)
        feedback.success(message)
    } catch (err) {
        feedback.error('复制失败，请手动复制')
        console.error('复制失败:', err)
    }
}

// 初始化行展开状态
const initRowExpansionState = (row) => {
    if (row.apiKeyExpanded === undefined) {
        row.apiKeyExpanded = false
    }
    if (row.secretKeyExpanded === undefined) {
        row.secretKeyExpanded = false
    }
    return ''
}

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiInterfaceAppListLists,
    params: queryParams
})

// 添加
const handleAdd = async () => {
    showEdit.value = true
    isAdd.value = true
    await nextTick()
    addRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true
    isAdd.value = false
    currentRow.value = data
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.setFormData(data)
}
// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiInterfaceAppListDelete({ id })
    getLists()
}
// 更新密钥
const handleUpdate = async (id: number | any[]) => {
    await feedback.confirm('确定要更新密钥？')
    await apiInterfaceAppListUpdateSecretKey({ id })
    getLists()
}

getLists()
</script>

<style scoped>
.key-container {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 1px;
    padding-left: 2px;
    padding-right: 2px;
}
</style>